package com.tanhua.dubbo.server.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.alibaba.dubbo.config.annotation.Service;

import com.tanhua.dubbo.server.pojo.UserLogin;

import org.apache.commons.lang3.time.DateUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service(version = "1.0.0")
public class DashboardApiImpl implements DashboardApi {


    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 根据起始时间查询mongoDB中的user_login表中的userId集合
     *
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public List<UserLogin> queryUserIdByTime(Long startTime, Long endTime) {

        //根据起始时间构建查询条件对象
        //创建一个时间条件
        Query query = new Query();

        Criteria criteria = new Criteria();
        criteria.andOperator(Criteria.where("logTime").gte(startTime), Criteria.where("logTime").lte(endTime));
        query.addCriteria(criteria);


        //查询MongoDB
        //List<UserLogin> userLoginList = this.mongoTemplate.find(query, UserLogin.class);
        List<UserLogin> userLoginList = this.mongoTemplate.findDistinct(query, "userId", "user_login", UserLogin.class);

        return userLoginList;
    }

    //查询指定时间段的活跃用户
    @Override
    public Integer queryActiveUser(Long beforeTime, Long nowTime) {

        //创建一个时间条件
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.andOperator(Criteria.where("logTime").gte(beforeTime), Criteria.where("logTime").lte(nowTime));
        query.addCriteria(criteria);

        //根据时间条件,查询mongoDB数据库,去重后的集合长度就是活跃用户
        List<UserLogin> userLoginList = this.mongoTemplate.findDistinct(query, "userId", "user_login", UserLogin.class);

        //返回近30天活跃用户数
        return userLoginList.size();
    }


    //查询指定时间的登录总次数
    @Override
    public Integer queryLogCount(Long startTime, Long endTime) {
        //创建一个时间条件
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.andOperator(Criteria.where("logTime").gte(startTime), Criteria.where("logTime").lte(endTime));
        query.addCriteria(criteria);

        //查询出总登录数
        long count = this.mongoTemplate.count(query, UserLogin.class);
        return Convert.toInt(count);
    }


    //查询出指定时间段内的所有的userLogin对象集合

    @Override
    public List<UserLogin> findAllByTime(Long startTime, Long endTime) {
        //创建一个时间条件
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.andOperator(Criteria.where("logTime").gte(startTime), Criteria.where("logTime").lte(endTime));
        query.addCriteria(criteria);

        return this.mongoTemplate.find(query, UserLogin.class);

    }

    //保存用户登录记录
    @Override
    public void saveUserLog(Long userId, String hostName) {
        UserLogin userLogin = new UserLogin();

        userLogin.setId(ObjectId.get());    //设置mongoDB主键
        userLogin.setUserId(userId);   //设置用户id
        userLogin.setLogTime(System.currentTimeMillis());   //设置当前登录时间

        //设置登陆者登出时间  登出时间=token失效时间
        Calendar c = Calendar.getInstance();
        c.add(Calendar.HOUR, 12);
        long logoutTime = c.getTime().getTime();
        userLogin.setLogoutTime(logoutTime);

        //登录设备(主机名称)
        userLogin.setEquipment(hostName);

        userLogin.setPlace("合肥");   //登录地点

        //生成假数据
        //toLog();

        //把userLogin对象(当前登陆者的登录记录)保存到mongoDB表中
        this.mongoTemplate.save(userLogin);
    }


    //生成假数据
    void toLog() {
        for (int i = 0; i < 300; i++) {

            UserLogin userLogin = new UserLogin();

            userLogin.setId(ObjectId.get());    //设置mongoDB主键

            Random random = new Random();
            int randomUserId = random.nextInt(100);
            userLogin.setUserId(Convert.toLong(randomUserId));   //设置登录用户id

            String time = "2020-11-06 12:13:33";
            long timeLong = DateUtil.parseDateTime(time).getTime();

            Date loginTime = DateUtils.addDays(new Date(timeLong), i);

            userLogin.setLogTime(loginTime.getTime());   //设置登录时间

            //设置登录时间
            Calendar c = Calendar.getInstance();
            c.setTime(loginTime);
            c.add(Calendar.HOUR, 12);
            long logoutTime = c.getTime().getTime();
            userLogin.setLogoutTime(logoutTime);

            userLogin.setEquipment("127.0.0.1");


            userLogin.setPlace("杭州");

            //把userLogin对象(当前登陆者的登录记录)保存到mongoDB表中
            this.mongoTemplate.save(userLogin);


        }


    }


    @Override
    public Integer queryActiveUserById(Long startTime, Long endTime, List<Object> ids) {
        //创建一个时间条件
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.andOperator(Criteria.where("logTime").gte(startTime), Criteria.where("logTime").lte(endTime));
        criteria.and("userId").in(ids);
        query.addCriteria(criteria);
        long count = this.mongoTemplate.count(query, UserLogin.class);

        return Convert.toInt(count);

    }
}
